<template>
  <div class="admin-container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="header-content">
        <el-button @click="goBack" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>系统管理</h2>
        <div></div>
      </div>
    </div>

    <!-- 统计卡片pai -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in statistics" :key="stat.title">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <el-icon class="stat-icon" :class="stat.color">
                <component :is="stat.icon" />
              </el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-title">{{ stat.title }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 管理功能 -->
    <div class="admin-functions">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="function-card" shadow="hover" @click="goToUserManagement">
            <div class="function-content">
              <el-icon class="function-icon"><User /></el-icon>
              <div class="function-title">用户管理</div>
              <div class="function-desc">管理系统用户和权限</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="function-card" shadow="hover" @click="goToDoctorManagement">
            <div class="function-content">
              <el-icon class="function-icon"><UserFilled /></el-icon>
              <div class="function-title">医生管理</div>
              <div class="function-desc">管理医生信息和排班</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="function-card" shadow="hover" @click="goToDepartmentManagement">
            <div class="function-content">
              <el-icon class="function-icon"><OfficeBuilding /></el-icon>
              <div class="function-title">科室管理</div>
              <div class="function-desc">管理医院科室信息</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 标签页 -->
    <div class="admin-tabs">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="用户管理" name="users">
          <div class="tab-content">
            <div class="section-header">
              <h3>用户列表</h3>
              <el-button type="primary" @click="addUser">
                <el-icon><Plus /></el-icon>
                添加用户
              </el-button>
            </div>
            
            <el-card class="table-card" shadow="never">
              <el-table :data="users" style="width: 100%" v-loading="loading">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="username" label="用户名" width="120" />
                <el-table-column prop="name" label="姓名" width="120" />
                <el-table-column prop="role" label="角色" width="100">
                  <template #default="scope">
                    <el-tag :type="getRoleType(scope.row.role)">
                      {{ getRoleText(scope.row.role) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机号" width="130" />
                <el-table-column prop="department" label="科室" width="100">
                  <template #default="scope">
                    {{ getDepartmentName(scope.row.department) }}
                  </template>
                </el-table-column>
                <el-table-column prop="title" label="职称" width="100" />
                <el-table-column label="操作" width="200">
                  <template #default="scope">
                    <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="挂号记录" name="appointments">
          <div class="tab-content">
            <div class="section-header">
              <h3>挂号记录管理</h3>
              <div class="header-actions">
                <el-select v-model="appointmentFilter" placeholder="状态筛选" style="width: 120px; margin-right: 10px;">
                  <el-option label="全部" value="" />
                  <el-option label="待确认" value="pending" />
                  <el-option label="已确认" value="confirmed" />
                  <el-option label="已取消" value="cancelled" />
                  <el-option label="已完成" value="completed" />
                </el-select>
                <el-button type="primary" @click="exportAppointments">
                  <el-icon><Download /></el-icon>
                  导出记录
                </el-button>
              </div>
            </div>
            
            <el-card class="table-card" shadow="never">
              <el-table :data="filteredAppointments" style="width: 100%" v-loading="appointmentsLoading">
                <el-table-column prop="id" label="预约ID" width="80" />
                <el-table-column prop="patientName" label="患者姓名" width="100" />
                <el-table-column prop="patientPhone" label="患者电话" width="120" />
                <el-table-column prop="doctorName" label="医生姓名" width="100" />
                <el-table-column prop="departmentName" label="科室" width="100" />
                <el-table-column prop="appointmentDate" label="预约日期" width="120" />
                <el-table-column prop="appointmentTime" label="预约时间" width="100" />
                <el-table-column prop="symptoms" label="症状描述" min-width="200" show-overflow-tooltip />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ getStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="150" />
                <el-table-column label="操作" width="200" fixed="right">
                  <template #default="scope">
                    <el-button size="small" @click="viewAppointmentDetail(scope.row)">查看</el-button>
                    <el-button 
                      size="small" 
                      type="success" 
                      v-if="scope.row.status === 'pending'"
                      @click="confirmAppointment(scope.row)"
                    >
                      确认
                    </el-button>
                    <el-button 
                      size="small" 
                      type="danger" 
                      v-if="scope.row.status === 'pending'"
                      @click="cancelAppointment(scope.row)"
                    >
                      取消
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="医生管理" name="doctors">
          <div class="tab-content">
            <div class="section-header">
              <h3>医生信息管理</h3>
              <el-button type="primary" @click="addDoctor">
                <el-icon><Plus /></el-icon>
                添加医生
              </el-button>
            </div>
            
            <el-card class="table-card" shadow="never">
              <el-table :data="doctors" style="width: 100%" v-loading="doctorsLoading">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="name" label="姓名" width="120" />
                <el-table-column prop="title" label="职称" width="120" />
                <el-table-column prop="department" label="科室" width="100">
                  <template #default="scope">
                    {{ getDepartmentName(scope.row.department) }}
                  </template>
                </el-table-column>
                <el-table-column prop="specialty" label="专长" min-width="200" show-overflow-tooltip />
                <el-table-column prop="experience" label="经验" width="100" />
                <el-table-column label="操作" width="200">
                  <template #default="scope">
                    <el-button size="small" @click="editDoctor(scope.row)">编辑</el-button>
                    <el-button size="small" @click="manageSchedule(scope.row)">排班</el-button>
                    <el-button size="small" type="danger" @click="deleteDoctor(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="科室管理" name="departments">
          <div class="tab-content">
            <div class="section-header">
              <h3>科室信息管理</h3>
              <el-button type="primary" @click="showDepartmentDialog()">
                <el-icon><Plus /></el-icon>
                添加科室
              </el-button>
            </div>
            
            <el-card class="table-card" shadow="never">
              <el-table :data="departments" style="width: 100%" v-loading="departmentsLoading">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="name" label="科室名称" width="150" />
                <el-table-column prop="description" label="描述" min-width="300" show-overflow-tooltip />
                <el-table-column prop="icon" label="图标" width="100" />
                <el-table-column label="操作" width="200">
                  <template #default="scope">
                    <el-button size="small" @click="showDepartmentDialog(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteDepartment(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 科室编辑对话框 -->
    <el-dialog 
      v-model="departmentDialogVisible" 
      :title="departmentForm.id ? '编辑科室' : '添加科室'"
      width="500px"
      @close="resetDepartmentForm"
    >
      <el-form 
        ref="departmentFormRef" 
        :model="departmentForm" 
        :rules="departmentRules" 
        label-width="80px"
      >
        <el-form-item label="科室名称" prop="name">
          <el-input v-model="departmentForm.name" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="departmentForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入科室描述"
          />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select v-model="departmentForm.icon" placeholder="请选择图标" style="width: 100%">
            <el-option label="🏥 医院" value="🏥" />
            <el-option label="⚕️ 医疗" value="⚕️" />
            <el-option label="👶 儿科" value="👶" />
            <el-option label="👩‍⚕️ 妇产科" value="👩‍⚕️" />
            <el-option label="👁️ 眼科" value="👁️" />
            <el-option label="🦷 口腔科" value="🦷" />
            <el-option label="💊 内科" value="💊" />
            <el-option label="🔪 外科" value="🔪" />
            <el-option label="🩺 诊断" value="🩺" />
            <el-option label="💉 注射" value="💉" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="departmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDepartment" :loading="savingDepartment">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { mockAPI } from '../utils/mockData'

export default {
  name: 'Admin',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const users = ref([])
    const statistics = ref([])
    const activeTab = ref('users')
    const appointments = ref([])
    const doctors = ref([])
    const departments = ref([])
    const appointmentFilter = ref('')
    const appointmentsLoading = ref(false)
    const doctorsLoading = ref(false)
    const departmentsLoading = ref(false)

    // 科室表单相关
    const departmentDialogVisible = ref(false)
    const departmentFormRef = ref()
    const savingDepartment = ref(false)
    const departmentForm = ref({
      id: null,
      name: '',
      description: '',
      icon: ''
    })

    const departmentRules = {
      name: [
        { required: true, message: '请输入科室名称', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入科室描述', trigger: 'blur' }
      ],
      icon: [
        { required: true, message: '请选择图标', trigger: 'change' }
      ]
    }

    // 获取系统统计信息
    const loadStatistics = async () => {
      try {
        const result = await mockAPI.getSystemStatistics()
        if (result.success) {
          const stats = result.data
          statistics.value = [
            {
              title: '总用户数',
              value: stats.totalUsers,
              icon: 'User',
              color: 'text-primary'
            },
            {
              title: '总预约数',
              value: stats.totalAppointments,
              icon: 'Calendar',
              color: 'text-success'
            },
            {
              title: '待确认预约',
              value: stats.pendingAppointments,
              icon: 'Clock',
              color: 'text-warning'
            },
            {
              title: '已确认预约',
              value: stats.confirmedAppointments,
              icon: 'Check',
              color: 'text-info'
            }
          ]
        }
      } catch (error) {
        console.error('获取统计信息失败:', error)
      }
    }

    // 获取用户列表
    const loadUsers = async () => {
      loading.value = true
      try {
        const result = await mockAPI.getAllUsers()
        if (result.success) {
          users.value = result.data
        }
      } catch (error) {
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }

    // 获取挂号记录
    const loadAppointments = async () => {
      appointmentsLoading.value = true
      try {
        const result = await mockAPI.getAllAppointments()
        if (result.success) {
          appointments.value = result.data
        }
      } catch (error) {
        ElMessage.error('获取挂号记录失败')
      } finally {
        appointmentsLoading.value = false
      }
    }

    // 获取医生列表
    const loadDoctors = async () => {
      doctorsLoading.value = true
      try {
        const result = await mockAPI.getAllDoctors()
        if (result.success) {
          doctors.value = result.data
        }
      } catch (error) {
        ElMessage.error('获取医生列表失败')
      } finally {
        doctorsLoading.value = false
      }
    }

    // 获取科室列表
    const loadDepartments = async () => {
      departmentsLoading.value = true
      try {
        const result = await mockAPI.getDepartments()
        if (result.success) {
          departments.value = result.data
        }
      } catch (error) {
        ElMessage.error('获取科室列表失败')
      } finally {
        departmentsLoading.value = false
      }
    }

    // 获取角色类型
    const getRoleType = (role) => {
      const typeMap = {
        'admin': 'danger',
        'doctor': 'warning',
        'patient': 'info'
      }
      return typeMap[role] || 'info'
    }

    // 获取角色文本
    const getRoleText = (role) => {
      const textMap = {
        'admin': '管理员',
        'doctor': '医生',
        'patient': '患者'
      }
      return textMap[role] || role
    }

    // 获取科室名称
    const getDepartmentName = (departmentId) => {
      if (!departmentId) return '-'
      const dept = departments.value.find(d => d.id === departmentId)
      return dept ? dept.name : '-'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待确认',
        'confirmed': '已确认',
        'cancelled': '已取消',
        'completed': '已完成'
      }
      return statusMap[status] || status
    }

    // 获取状态类型
    const getStatusType = (status) => {
      const typeMap = {
        'pending': 'warning',
        'confirmed': 'success',
        'cancelled': 'danger',
        'completed': 'info'
      }
      return typeMap[status] || 'info'
    }

    // 过滤挂号记录
    const filteredAppointments = computed(() => {
      if (!appointmentFilter.value) {
        return appointments.value
      }
      return appointments.value.filter(appointment => appointment.status === appointmentFilter.value)
    })

    // 导航方法
    const goBack = () => {
      router.go(-1)
    }

    const goToUserManagement = () => {
      activeTab.value = 'users'
    }

    const goToDoctorManagement = () => {
      activeTab.value = 'doctors'
    }

    const goToDepartmentManagement = () => {
      activeTab.value = 'departments'
    }

    // 用户管理方法
    const addUser = () => {
      ElMessage.success('添加用户功能开发中...')
    }

    const editUser = (user) => {
      ElMessage.success(`编辑用户 ${user.name} 功能开发中...`)
    }

    const deleteUser = async (user) => {
      try {
        await ElMessageBox.confirm(`确定要删除用户 ${user.name} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        ElMessage.success('删除成功')
        loadUsers()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 挂号记录管理方法
    const viewAppointmentDetail = (appointment) => {
      ElMessage.success(`查看预约详情：${appointment.patientName} - ${appointment.doctorName}`)
    }

    const confirmAppointment = async (appointment) => {
      try {
        await ElMessageBox.confirm(`确定要确认预约 ${appointment.patientName} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        appointment.status = 'confirmed'
        ElMessage.success('预约已确认')
        loadAppointments()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }

    const cancelAppointment = async (appointment) => {
      try {
        await ElMessageBox.confirm(`确定要取消预约 ${appointment.patientName} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        appointment.status = 'cancelled'
        ElMessage.success('预约已取消')
        loadAppointments()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }

    const exportAppointments = () => {
      ElMessage.success('挂号记录导出功能开发中...')
    }

    // 医生管理方法
    const addDoctor = () => {
      ElMessage.success('添加医生功能开发中...')
    }

    const editDoctor = (doctor) => {
      ElMessage.success(`编辑医生 ${doctor.name} 功能开发中...`)
    }

    const manageSchedule = (doctor) => {
      ElMessage.success(`管理医生 ${doctor.name} 排班功能开发中...`)
    }

    const deleteDoctor = async (doctor) => {
      try {
        await ElMessageBox.confirm(`确定要删除医生 ${doctor.name} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        ElMessage.success('删除成功')
        loadDoctors()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    // 科室管理方法
    const showDepartmentDialog = (department = null) => {
      if (department) {
        // 编辑模式
        departmentForm.value = {
          id: department.id,
          name: department.name,
          description: department.description,
          icon: department.icon
        }
      } else {
        // 添加模式
        departmentForm.value = {
          id: null,
          name: '',
          description: '',
          icon: ''
        }
      }
      departmentDialogVisible.value = true
    }

    const resetDepartmentForm = () => {
      departmentForm.value = {
        id: null,
        name: '',
        description: '',
        icon: ''
      }
      if (departmentFormRef.value) {
        departmentFormRef.value.resetFields()
      }
    }

    const saveDepartment = async () => {
      try {
        await departmentFormRef.value.validate()
        savingDepartment.value = true

        if (departmentForm.value.id) {
          // 编辑模式
          const result = await mockAPI.updateDepartment(departmentForm.value)
          if (result.success) {
            ElMessage.success('科室更新成功')
            departmentDialogVisible.value = false
            loadDepartments()
          }
        } else {
          // 添加模式
          const result = await mockAPI.createDepartment(departmentForm.value)
          if (result.success) {
            ElMessage.success('科室添加成功')
            departmentDialogVisible.value = false
            loadDepartments()
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      } finally {
        savingDepartment.value = false
      }
    }

    const deleteDepartment = async (department) => {
      try {
        await ElMessageBox.confirm(`确定要删除科室 ${department.name} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const result = await mockAPI.deleteDepartment(department.id)
        if (result.success) {
          ElMessage.success('删除成功')
          loadDepartments()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    onMounted(() => {
      loadStatistics()
      loadUsers()
      loadAppointments()
      loadDoctors()
      loadDepartments()
    })

    return {
      loading,
      users,
      statistics,
      activeTab,
      appointments,
      doctors,
      departments,
      appointmentFilter,
      appointmentsLoading,
      doctorsLoading,
      departmentsLoading,
      filteredAppointments,
      departmentDialogVisible,
      departmentFormRef,
      departmentForm,
      departmentRules,
      savingDepartment,
      getRoleType,
      getRoleText,
      getDepartmentName,
      getStatusText,
      getStatusType,
      goBack,
      goToUserManagement,
      goToDoctorManagement,
      goToDepartmentManagement,
      addUser,
      editUser,
      deleteUser,
      viewAppointmentDetail,
      confirmAppointment,
      cancelAppointment,
      exportAppointments,
      addDoctor,
      editDoctor,
      manageSchedule,
      deleteDoctor,
      showDepartmentDialog,
      resetDepartmentForm,
      saveDepartment,
      deleteDepartment
    }
  }
}
</script>

<style scoped>
.admin-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-btn {
  color: white;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.back-btn .el-icon {
  margin-right: 5px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
}

.stats-section {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.stat-card {
  border: none;
  border-radius: 15px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  font-size: 40px;
  padding: 15px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-title {
  font-size: 14px;
  color: #666;
}

.admin-functions {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.function-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  border-radius: 15px;
}

.function-card:hover {
  transform: translateY(-5px);
}

.function-content {
  text-align: center;
  padding: 30px 20px;
}

.function-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 15px;
}

.function-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.function-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.admin-tabs {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.tab-content {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-card {
  border: none;
  border-radius: 15px;
}

.text-primary {
  color: #409EFF;
}

.text-success {
  color: #67C23A;
}

.text-warning {
  color: #E6A23C;
}

.text-info {
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .stats-section .el-col {
    margin-bottom: 15px;
  }
  
  .admin-functions .el-col {
    margin-bottom: 15px;
  }
}
</style> 